package com.demo.service;

import com.demo.mapper.CountryMapper;
import com.demo.model.Country;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.StringUtil;

import java.util.List;

/**
 * IntelliJ IDEA.
 * User: lwb
 * Date: 2017/10/17
 * Time: 14:31
 * function:
 */
@Service
public class CountryService {

    @Autowired
    CountryMapper countryMapper;

    //手动回滚
    //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

    public void create(Country country) {
        countryMapper.insertSelective(country);
    }

    public void create1( ) {
        Country country = new Country();
        country.setCountryName("test rallback");
        country.setCountryCode("code code");
        countryMapper.insertSelective(country);
        //手动回滚操作
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    }

    public void update(Country country) {
        countryMapper.updateByPrimaryKeySelective(country);
    }

    public void delete(Country country) {
        countryMapper.deleteByPrimaryKey(country);
    }

    public List<Country> selectByCountry(Country country, int page, int rows) {


        Example example = new Example(Country.class);
        //example.setOrderByClause("GMT_UPDATE DESC");//注意此处是列名称，不是属性名。
        Example.Criteria criteria = example.createCriteria();
        if (StringUtil.isNotEmpty(country.getCountryName())) {
            //注意property和model中对应的property名一致
            criteria.andLike("countryName", "%" + country.getCountryName() + "%");
        }
        if (StringUtil.isNotEmpty(country.getCountryCode())) {
            criteria.andLike("countryCode", "%" + country.getCountryCode() + "%");
        }
        if (country.getId() != null) {
            criteria.andEqualTo("id", country.getId());
        }
        //分页查询
        PageHelper.startPage(page, rows);
        //order  注意此处是列名称，不是属性名。
        PageHelper.orderBy("country_name desc");
        return countryMapper.selectByExample(example);
    }
}
